from django.http import HttpResponse
from django.shortcuts import render, redirect
from django import forms

from mysite import models
from mysite.utills.code import check_code
from mysite.utills.encrypt import md5


class LoginForm(forms.Form):

    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'})
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'}, render_value=True)
    )

    # 狗子方法，加密密码md5
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)


def login(request):
    """ 登录 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证码校验
        user_insert_code = form.cleaned_data.pop['code']
        code = request.session.get('image_code', "")
        if code.upper() != user_insert_code:
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})

        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error("password", "用户名或密码错误")
            # form.add_error("username", "用户名或密码错误")
            return render(request, 'login.html', {'form': form})

        # 网站生成随机字符串; 写到用户浏览器的cookie中；在写入到session中；
        request.session["info"] = {'id': admin_object.id, 'name': admin_object.username}
        # session可以保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)

        return redirect("/admin/list/")

    return render(request, 'login.html', {'form': form})

def image_code(request):
    """生成图片验证码"""

    # 调用pillow生成图片
    img, code_string = check_code()
    # 将验证码写入到session中，
    request.session['image_code'] = code_string
    # 给session设置60秒超时
    request.session.set_expiry(60)

    from io import BytesIO
    stream = BytesIO()
    img.save(stream, 'png')
    stream.getvalue()

    return HttpResponse(stream.getvalue())

def logout(request):
    """注销"""
    request.session.clear()

    return redirect('/login/')

